﻿using DidaCode.Workflow.NodeAttribute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DidaCode.Workflow.NodeBase
{
    public static class NodeFactory
    {
        private static readonly Lazy<Dictionary<string, Type>> NodeTypesLazy = new Lazy<Dictionary<string, Type>>(LoadNodeTypes);

        private static Dictionary<string, Type> LoadNodeTypes()
        {
            return Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.GetCustomAttribute<NodeTypeAttribute>() != null)
                .ToDictionary(t => t.GetCustomAttribute<NodeTypeAttribute>().Name, t => t);
        }

        private static Dictionary<string, Type> NodeTypes => NodeTypesLazy.Value;

        public static INode<TInput, TOutput> CreateNode<TInput, TOutput>(string nodeName, string switchConfig)
        {
            if (NodeTypes.TryGetValue(nodeName, out var nodeType))
            {
                return (INode<TInput, TOutput>)Activator.CreateInstance(nodeType, args: switchConfig);
            }
            throw new InvalidOperationException($"Unknown node type: {nodeName}");
        }



        /// <summary>
        /// 获取节点对应的类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>

        public static Type NodeType(string NodeName)
        {
            if (NodeTypes.TryGetValue(NodeName, out var type))
            {
                return type;
            }
            return default;
        }

        /// <summary>
        /// 获取节点对应的类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>

        public static string NodeName(Type type)
        {
            var typeFirst = NodeTypes.FirstOrDefault(t => t.Value == type);
            if (typeFirst.Value != null)
            {
                return typeFirst.Key;
            }
            return string.Empty;
        }

    }
}
